﻿using PluginAPI.Core;
using System.Collections;
using UnityEngine;
using Utils;


namespace ModuleHeal.Component
{
    /// <summary>
    /// 
    /// </summary>
    public class HealComponent : MonoBehaviour
    {
        [Tooltip("缓存位置")] Vector3 positionLast = Vector3.zero;
        [Tooltip("实时位置")] Vector3 positionNew  = Vector3.zero;
        [Space]
        [Tooltip("协程等待")] WaitForSeconds waitTime = new WaitForSeconds(1f);
        [Tooltip("计时器项")] uint count = 0;
        [Tooltip("计时器项")] Coroutine m_COR;
        [Space]
        [Tooltip("玩家信息")] Player m_Player;
        [Tooltip("玩家信息")] float m_MaxHealth;


        public void Bind(Player player, float maxHealth)
        {
            TimeCoroutine.Stop(m_COR);
            this.m_Player = player;
            this.m_MaxHealth = maxHealth;

            TimeCoroutine.Start(IDoHeal());
        }

        private IEnumerator IDoHeal()
        {
            while (true)
            {

                yield return waitTime;


                // 更新时间
                count++;
                // 更新位置
                positionLast = positionNew;
                positionNew = transform.position;


                bool isHeal = positionLast == positionNew;
                if (isHeal)
                {
                    bool isTimeReady = count >= CodeLoad.Singleton.Config.WaitingTime;

                    if (isTimeReady)
                    {
                        bool isUpper = m_Player.Health >= m_Player.MaxHealth;

                        if (!isUpper)
                        {
                            PlayerUtils.Heal(m_Player, CodeLoad.Singleton.Config.HealAmount, false);
                        }          
                    }
                }
                else
                {
                    count = 0;
                }
            }
        }

        public void OnDestroy()
        {
            TimeCoroutine.Stop(m_COR);
            this.m_COR = null;
        }
    }
}
